package org.xnat.xnatfs.asset;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.InputStream;

import org.junit.Before;
import org.junit.Test;

public class TestHttpResponseStringAsset extends HttpResponseAssetTestCase {
  private HttpResponseStringAsset asset;

  @Before
  public void setUp () throws Exception {
    super.setUp ();
  }

  @Test
  public void shouldProvideStringVersionOfInputStream () throws Exception {
    when ( entity.getContent () ).thenReturn ( StreamUtils.toStream ( SAMPLE_STRING ) );
    asset = new HttpResponseStringAsset ( response );

    assertEquals ( SAMPLE_STRING, asset.getContent () );
    verify ( entity ).consumeContent ();
  }

  @Test
  public void shouldPropogateEntityErrorAndCloseResource () throws Exception {
    when ( entity.getContent () ).thenThrow ( new IOException ( "fake exception" ) );

    try {
      asset = new HttpResponseStringAsset ( response );
      fail ( "Expected exception" );
    } catch ( IOException e ) {
      // expected
    }
    verify ( entity ).consumeContent ();
  }

  @Test
  public void shouldPropogateStreamErrorAndCloseResource () throws Exception {
    InputStream stream = mock ( InputStream.class );
    when ( stream.read () ).thenThrow ( new IOException ( "fake exception" ) );
    when ( entity.getContent () ).thenReturn ( stream );

    try {
      asset = new HttpResponseStringAsset ( response );
      fail ( "Expected exception" );
    } catch ( IOException e ) {
      // expected
    }
    verify ( stream ).close ();
    verify ( entity ).consumeContent ();
  }

}
